<template>
  <div>
    <el-card>
      <el-input
        placeholder="请输入内容"
        v-model="query"
        style="width: 300px; margin-right: 15px"
        @change="serch"
      >
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
      <!-- 用户数据渲染 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="#" width="80"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180"> </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="Switch(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="alter(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="remove(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="ChangeSize"
        @current-change="ChangeNum"
        :current-page="pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%">
      <!-- 对话框主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户弹框 -->

    <el-dialog title="修改用户" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="用户名称" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input v-model="form.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="win(form)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的手机号码"));
    };
    return {
      tableData: [], //数据存储
      query: "", //搜索关键字
      pagenum: 1, //当前页码数
      pagesize: 5, //每页显示的条数
      menus: [],
      form: {
        username: "",
        email: "",
        mobile: "",
      },
      dialogFormVisible: false,
      formLabelWidth: "120px",
      //获取查询用户信息的参数
      queryInfo: {
        // 查询的条件
        query: "",
        // 当前的页数，即页码
        pagenum: 1,
        // 每页显示的数据条数
        pagesize: 2,
      },
      //保存请求回来的用户列表数据
      userList: [],
      total: 0,
      //是否显示添加用户弹出窗
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3~10个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "用户名在6~15个字符之间",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "邮箱格式不正确，请重新输入",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            validator: checkMobile,
            message: "手机号码不正确，请重新输入",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.usersList();
    this.$http.get("menus").then((res) => {
      // console.log(res);
      this.menus = res.data.data;
    });
  },
  methods: {
    // 用户列表
    usersList() {
      this.$http
        .get(
          `users?query=${this.query}&pagenum=${this.pagenum}&pagesize=${this.pagesize}`
        )
        .then((res) => {
          console.log(res);
          this.tableData = res.data.data.users;
          this.total = res.data.data.total;
        });
    },

    // 删除操作
    remove(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete(`users/${id}`).then((res) => {
            console.log(res);
            if (res.data.meta.status == 200) {
              this.$message.success(res.data.meta.msg);
              this.usersList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 修改状态
    Switch(obj) {
      this.$http.put(`users/${obj.id}/state/${obj.mg_state}`).then((res) => {
        if (res.data.meta.status == 200) {
          this.$message.success(res.data.meta.msg);
        }
      });
    },

    ChangeNum(num) {
      this.pagenum = num;
      this.usersList();
    },
    ChangeSize(size) {
      this.pagesize = size;
      this.usersList();
    },
    serch() {
      this.usersList();
    },
    // 点击修改图标让弹框显示
    alter(obj) {
      // console.log(obj);
      this.form = obj;
      this.dialogFormVisible = true; //让修改弹框显示
    },

    // 修改点击确定
    async win(obj) {
      this.dialogFormVisible = false; //让修改弹框消失
      var res = await this.$http.put(`users/${obj.id}`, this.form);
      console.log(res);
      this.form = obj; //数据回填
      this.$message.success("修改成功"); //修改成功的提示信息
    },

    addUser() {
      //点击确定按钮，添加新用户
      //调用validate进行表单验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写完整用户信息");
        //发送请求完成添加用户的操作
        const { data: res } = await this.$http.post("users", this.addForm);
        //判断如果添加失败，就做提示
        if (res.meta.status == 201) {
          // 添加成功的提示
          this.$message.success("添加用户成功");
          // //关闭对话框
          this.addDialogVisible = false;
          // //重新请求最新的数据
          this.usersList();
        }
      });
    },
    addDialogClosed() {
      //对话框关闭之后，重置表达
      this.$refs.addFormRef.resetFields();
    },
  },
  computed: {},
  watch: {},
};
</script>

<style scoped>
.el-table {
  margin-top: 15px;
}
</style>
